<template>
  <a-spin :spinning="confirmLoading">

    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row><a-col :span="6" ><tsl-step :list="steplist" :currentStatus="model.status"></tsl-step></a-col></a-row>
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="入库单编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入入库单编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storageType">
              <j-dict-select-tag style="width: 200px" :disabled="storageTypeDisabled" type="list" v-model="model.storageType"
                                 dictCode="rk_type" placeholder="请选择入库类型" :disabledVal="3"/>
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="6" v-show="false">-->
<!--            <a-form-model-item label="业务节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">-->
<!--              <a-space>-->
<!--                &lt;!&ndash;                <a-input v-model="model.code" placeholder="请输入单据编号" ></a-input>&ndash;&gt;-->
<!--                <j-dict-select-tag style="width: 200px" disabled type="list" v-model="model.businessNode"-->
<!--                                   dictCode="business_node_type" placeholder="请选择业务节点" />-->
<!--                <a-button :disabled="typeof model.noticeId != 'undefined'" style="margin-left: -10px" @click="onSearchBussiness">请选择业务节点</a-button>-->
<!--              </a-space>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="6" v-show="false">-->
<!--            <a-form-model-item label="物料大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialTypeName">-->
<!--              <a-input v-model="model.materialTypeName" disabled placeholder="物料大类" ></a-input>-->
<!--              <a-input v-model="model.materialTypeCode" v-show="false" placeholder="物料大类" ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="6" v-show="false">-->
<!--            <a-form-model-item label="业务类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="businessType">-->
<!--              <j-dict-select-tag disabled type="list" v-model="model.businessType"-->
<!--                                 dictCode="business_type" placeholder="请选择业务类型"/>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="8" >-->
<!--            <a-form-model-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storageType">-->
<!--              <j-dict-select-tag  placeholder="请选择入库类型" v-model="model.storageType" dictCode="rk_type"   @change="storageTypeChanged" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="8" >-->
<!--            <a-form-model-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">-->
<!--              <a-button @click="onSearchSuper"> 选择上级单据</a-button>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="入库单明细" :key="refKeys[0]" :forceRender="true">
        <a-card title="收货信息" :bordered='false'>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussStorageDetailTable.loading"
          :columns="bussStorageDetailTable.columns"
          :dataSource="bussStorageDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :toolbarConfig="{slot: ['prefix', 'suffix'], btn: [ 'remove', 'clearSelection']}"
        >
          <template    v-slot:toolbarSuffix>
              <a-button @click='addMaterial' v-if='!storageTypeDisabled'>新增</a-button>
              <a-button @click='handleCK' >添加车辆信息</a-button>
<!--            <a-button @click='' v-show="model.storageType == 0">新增</a-button>-->
            <!--  <a-button @click='addMaterial' >新增</a-button>-->
<!--            <a-button @click='editMaterial' v-show=" bussStorageDetailTable.dataSource.length > 0 " >编辑</a-button>-->
            <!--          <a-button @click='addMaterial' v-if='!procurementShow && model.type'>新增物料</a-button>-->
          </template>
          <template v-slot:supplierId="props">
            <tsl-mat-supplier v-model="props.value" :isDisabled="bussinessDisable" :rowData='props'
                              @handlerOk="supplierOk"></tsl-mat-supplier>
          </template>
          <template v-slot:erpLocationName="props">
            <tsl-warehouse v-model="props.value" :rowData='props' @handlerOk="warehouseOk"></tsl-warehouse>
          </template>
<!--          <template    v-slot:toolbarSuffix>-->
<!--            <a-button @click='addMaterial' v-show='!model.materialType || model.materialType != 7'>新增物料</a-button>-->
<!--          </template>-->
        </j-vxe-table>
        </a-card>
        <a-card title="车辆信息" :bordered='false'>
          <j-vxe-table
            keep-source
            :ref="refKeys[1]"
            :loading="bussStorageCarinfoTable.loading"
            :columns="bussStorageCarinfoTable.columns"
            :dataSource="bussStorageCarinfoTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :toolbar="true"
            :autoResize="true"
            :toolbarConfig="{slot: ['prefix', 'suffix'], btn: ['clearSelection']}"
            @edit-closed="editClosedEvent"
          >
            <template    v-slot:toolbarSuffix>
              <a-button @click='deleteCarinfo' >删除</a-button>
              <a-button @click='clearCheck("car")' >清空选择</a-button>
            </template>
          </j-vxe-table>
        </a-card>
      </a-tab-pane>
      <a-tab-pane tab="状态履历修改" key="history"  :forceRender="true">
        <a-card :bordered='false'>
          <tsl-history dataTable="buss_storage" :dataId="model.id"></tsl-history>
        </a-card>
      </a-tab-pane>
    </a-tabs>
    <buss-storage-notice ref='notice' @handlerOk='noticeOk' checkval="checkbox"></buss-storage-notice>
    <erp-good-list ref='good'
                   @handlerOk='goodOk'
                   checkval='checkbox' :category="model.materialTypeCode"></erp-good-list>
    <bussiness-type-list ref="bussinessType" @handleOk="bussinessOk" :businessNode="1" :businessType="3"></bussiness-type-list>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import BussStorageNotice  from '@/views/modules/business/BussStorageNoticeList'
  import ErpGoodList from '@/views/modules/goods/ErpGoodsListModal'
  import DetailsModal from '@/components/modal/DetailsModal'
  import { filterDictTextByCache } from '@comp/dict/JDictSelectUtil'
  import TslSelectLocation from '@comp/tsl/TslSelectLocation.vue'
  import TslSelectGoods  from '@comp/tsl/TslSelectGoods.vue'
  import TslSelectGoodsCategory from '@comp/tsl/TslSelectGoodsCategory'
  import TslStep from '@/components/tsl/TslStep'
  import moment from 'dayjs'
  import TslMatSupplier from '@comp/tsl/cell/TslMatSupplier.vue'
  import TslErpCustomer from '@comp/tsl/TslErpCustomer.vue'
  import TslWarehouse from '@comp/tsl/TslWarehouse.vue'
  import TslHistory from '@comp/tsl/TslHistory.vue'
  import BussinessTypeList from '@/views/modules/business/BusinessTypeList'

  export default {
    name: 'BussStorageForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,BussStorageNotice,ErpGoodList,DetailsModal,TslSelectLocation,TslSelectGoodsCategory,TslSelectGoods,TslStep,
      TslMatSupplier,TslErpCustomer,TslWarehouse,TslHistory,BussinessTypeList
    },
    data() {
      return {
        moment,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
         },
        rules: {

        },
        steplist:[
          {title:'草稿'},{title:'状态之间转换'}
        ],
        storageTypeDisabled: false,
        noticedSelectRows: [],
        bussinessDisable: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 0,
        validatorRules: {
        },
        refKeys: ['bussStorageDetailTable', 'bussStorageCarinfoTable'],
        tableKeys:['bussStorageDetailTable', 'bussStorageCarinfoTable'],
        activeKey: 'bussStorageDetailTable',
        supplierOptions: [],
        // 入库单明细
        tableRef: '',
        CarTableRef: '',
        bussStorageDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '行项目',
              key: 'rowNum',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '入库备注',
              key: 'remark',
              type: JVXETypes.input,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料种类',
              key: 'materialTypeName',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编号',
              key: 'materialCode',
              type: JVXETypes.normal,
              width: '200px',
            },
            {
              title: '物料名称',
              key: 'materialName',
              type: JVXETypes.normal,
              width: '100px',
            },
            {
              title: '规格',
              key: 'spec',
              type: JVXETypes.normal,
              width: '100px',
            },
            {
              title: '单位',
              key: 'meUnit',
              type: JVXETypes.select,
              width: '100px',
              dictCode: 'ji_unit',
              disabled: true
            },
            {
              title: '关联单据编号',
              key: 'superiorCode',
              type: JVXETypes.normal,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '数量',
              key: 'num',
               type: JVXETypes.input,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '辅助数量',
              key: 'supportNum',
              type: JVXETypes.normal,
              width: '100px',
            },
            {
              title: '辅助单位',
              key: 'supportUnit',
              type: JVXETypes.normal,
              width: '100px',
            },
            {
              title: '入库数量',
              key: 'storageNum',
              type: JVXETypes.inputNumber,
              width: '100px',
            },
            {
              title: '客户物料编号',
              key: 'customerMaterialNo',
               type: JVXETypes.input,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '生产车间',
              key: 'workshop',
              type: JVXETypes.select,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              dictCode: 'erp_production_workshop,name,id',
              disabled: false
            },
            {
              title: '供应商',
              key: 'supplierId',
              type: JVXETypes.slot,
              width: '200px',
              slotName: 'supplierId',
            },
            // {
            //   title: '供应商名称',
            //   key: 'supplierName',
            //   type: JVXETypes.input,
            //   width:"200px",
            //   placeholder: '请输入${title}',
            //   defaultValue:'',
            // },
            {
              title: '客户名称',
              key: 'customerName',
              type: JVXETypes.input,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '质检状态',
              key: 'qcStatus',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '仓库编号',
              key: 'erpWarehouseCode',
              type: JVXETypes.hidden,
              width: '100px',
            },
            {
              title: '仓库名称',
              key: 'erpWarehouseName',
              type: JVXETypes.hidden,
              width: '100px',
            },
            {
              title: '库位编码',
              key: 'erpLocationCode',
              type: JVXETypes.hidden,
              width: '100px',
            },
            {
              title: '库位名称',
              key: 'erpLocationName',
              type: JVXETypes.hidden,
              width: '100px',
            },
            {
              title: '库位名称',
              key: 'erpLocationId',
              type: JVXETypes.slot,
              width: '200px',
              slotName: "erpLocationName"
            },
            {
              title: '批次号',
              key: 'batchNum',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料批号',
              key: 'materialLotNum',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '入库日期',
              key: 'warehouseDate',
              type: JVXETypes.date,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '生产日期',
              key: 'createDate',
              type: JVXETypes.date,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '限用日期',
              key: 'expiryDate',
              type: JVXETypes.date,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '当前状态',
              key: 'stauts',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '质检状态',
              key: 'qcStatus',
              type: JVXETypes.select,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
              dictCode: 'zj_status',
              disabled: false
            },
            {
              title: '经办人',
              key: 'createBy',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '经办部门',
              key: 'createBy',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '制单人',
              key: 'createBy',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '制单日期',
              key: 'createTime',
              type: JVXETypes.normal,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        bussStorageCarinfoTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'id',
              key: 'id',
              type: JVXETypes.hidden,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '行项目',
              key: 'rowNum',
              type: JVXETypes.normal,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '通知单id',
              key: 'noticeId',
              type: JVXETypes.hidden,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '车牌号',
              key: 'carNum',
              type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编号',
              key: 'materialCode',
              type: JVXETypes.normal,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料名称',
              key: 'materialName',
              type: JVXETypes.normal,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'meUnit',
              type: JVXETypes.select,
              width: '150px',
              dictCode: 'ji_unit',
              disabled: true
            },
            {
              title: '原发数',
              key: 'originalNum',
              type: JVXETypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '实际数量',
              key: 'actualNum',
              type: JVXETypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
              type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            // {
            //   title: '操作',
            //   key: 'action',
            //   type: JVXETypes.slot,
            //   fixed: 'right',
            //   minWidth: '200px',
            //   align: 'center',
            //   slotName: 'action',
            // }
          ]
        },
        url: {
          add: "/business/bussStorage/add",
          edit: "/business/bussStorage/edit",
          queryById: "/business/bussStorage/queryById",
          bussStorageDetail: {
            list: '/business/bussStorage/queryBussStorageDetailByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    mounted() {
      this.getAllTable().then(tables=>{
        this.tableRef = tables[0]
        this.CarTableRef = tabless[1]
      })
      setTimeout(() => {
          if(!this.model.id){
            let rows = this.tableRef.getNewDataWithId()
            this.tableRef.removeRowsById(rows[0].id)
          }
        },100)
    },
    methods: {
      handleCK(){
        // 添加车辆信息
        let rows =  this.tableRef.selectedRows;
        if(rows.length === 0 || rows.length > 1){
          this.$message.warn('请选择一个收货信息！')
          return;
        }
        rows.forEach(item=>{
          let detail = {
            actualNum: '',
            originalNum: '',
            rowNum: item.rowNum,
            materialId: item.materialId,
            materialCode: item.materialCode,
            materialName: item.materialName,
            meUnit: item.meUnit
          }
          this.bussStorageCarinfoTable.dataSource.push(detail)
        })
      },
      deleteCarinfo(props){
        // 删除物料
        let rows =  this.CarTableRef.selectedRows;
        if(rows.length<=0){
          this.$message.warn('请选择车辆信息！')
          return;
        }
        rows.forEach(row=>{
          this.bussStorageNoticeCarinfoTable.dataSource = this.bussStorageNoticeCarinfoTable.dataSource.filter(item=>item.id !== row.id)
        })
      },
      editClosedEvent ({ row, column }){
        // 车辆数量修改，物料数量跟着变动
        // let xTable = this.$refs.bussStorageNoticeCarinfo
        // let field = column.property
        // let cellValue = row[field]
        // // 判断单元格值是否被修改
        // this.$nextTick(() => {
        //   if (xTable.isUpdateByRow(row, field)) {
        //     let { rowNum, materialId, originalNum, actualNum } = row
        //     this.bussStorageNoticeMaterialTable.dataSource.forEach(mater => {
        //       mater.actualNum = 0
        //       mater.originalNum = 0
        //       this.bussStorageNoticeCarinfoTable.dataSource.forEach(car =>{
        //         if(car.rowNum === mater.rowNum && mater.materialId === car.materialId ){
        //           mater.actualNum +=  car.actualNum
        //           mater.originalNum += car.originalNum
        //         }
        //       })
        //     });
        //     this.NoticeMaterialTable.resetScrollTop();
        //   }
        // })
      },
      clearCheck(obj){
        if(obj == 'car'){
          this.CarTableRef.clearSelection();
        }
        // else{
        //   this.NoticeMaterialTable.clearSelection();
        // }
      },
      bussinessOk({rows,callback}){
        const row = rows[0]
        this.$set(this.model,'businessNode',row.businessNode)
        this.$set(this.model,'materialTypeName',row.materialTypeName)
        this.$set(this.model,'businessType',row.businessType)
        this.$set(this.model,'materialTypeCode',row.materialTypeCode)
        callback(true)
      },
      onSearchBussiness(){
        this.$nextTick(()=>{
          this.$refs.bussinessType.add();
        })
      },
      warehouseOk({result,row}){
        this.bussStorageDetailTable.dataSource.forEach(item=>{
          if(item.materialId == row.materialId && item.rowNum == row.rowNum){
            item.erpLocationId = result.id
            item.erpLocationName = result.name
            item.erpLocationCode = result.code
            item.erpWarehouseName = result.warehouseName
            item.erpWarehouseCode = result.warehouseCode
          }
        })
        this.tableRef.resetScrollTop();
      },
      supplierOk({row,value}){
        this.bussStorageDetailTable.dataSource.forEach(item=>{
          if(item.materialId == row.materialId && item.rowNum == row.rowNum){
            item.supplierId = value
          }
        })
        this.tableRef.resetScrollTop();
      },
      addNoticed(noticedSelectRows){
          if(noticedSelectRows.length>0){
            this.noticedSelectRows = noticedSelectRows
          }
          this.storageTypeDisabled = true
          const rows = this.noticedSelectRows
          this.confirmBussiness( this.noticedSelectRows[0])
          this.model.noticeId = this.noticedSelectRows[0].id
          this.model.storageType = 3
          getAction('/business/bussStorageNotice/queryBussStorageNoticeMaterialByMainId',{id:noticedSelectRows[0].id})
            .then(res=>{
              if(res.success){
                let { result } = res
                //判断是否存在不同的供应商
                result.forEach((item,index)=>{
                  let detail = {
                    noticeDetailId: item.id,
                    superiorCode: this.noticedSelectRows[0].code,
                    materialCode: item.materialCode,
                    materialName: item.materialName,
                    materialId: item.materialId,
                    materialTypeName: item.materialTypeName,
                    supplierId: item.supplierId,
                    num: item.actualNum,
                    spec: item.spec,
                    meUnit: item.meUnit,
                    createDate: item.createDate,
                    expiryDate: item.expiryDate,
                    lotNumber: item.lotNumber,
                    materialLotNum: item.materialLotNum,
                    erpLocationCode: item.erpLocationCode,
                    erpLocationName: item.erpLocationName,
                    erpLocationId: item.erpLocationId,
                    erpWarehouseName: item.erpWarehouseName,
                    erpWarehouseCode: item.erpWarehouseCode,
                    // rowNum: this.getRowNum(),
                    rowNum: item.rowNum,
                    warehouseDate: moment(new Date()).format('YYYY-MM-DD'),
                  }
                  this.bussStorageDetailTable.dataSource.push(detail)
                })
              }
            })
          // this.formatterDatas();
      },
      confirmBussiness(row){
        // 确定业务类型
        //materialTypeCode 物料种类   原料2 包材4
        // businessType 业务类型 0
        this.$set(this.model,'businessNode',1)
        this.$set(this.model,'materialTypeName',row.materialTypeName)
        this.$set(this.model,'materialTypeCode',row.materialTypeCode)
        this.$set(this.model,'businessType',0)
        this.bussinessDisable = true
      },

      // supplierOk({data}){
      //   this.$refs.details.updateData('supplierId',data.id)
      //   this.$refs.details.updateData('supplierCode',data.code)
      // },
      locationOk(data){
        this.$refs.details.updateData('erpWarehouseCode',data.warehouseCode)
        this.$refs.details.updateData('erpWarehouseName',data.warehouseName)
        this.$refs.details.updateData('erpLocationCode',data.code)
        this.$refs.details.updateData('erpLocationName',data.name)
        this.$refs.details.updateData('erpLocationId',data.id)
      },
      storageTypeChanged(data){
        this.bussStorageDetailTable.dataSource = []
      },
      editMaterial(){
        let rows = this.tableRef.selectedRows
        if(rows.length == 0 || rows.length > 1){
          this.$message.warn('请选择一个要编辑的入库信息！')
          return;
        }
        const index = this.bussStorageDetailTable.dataSource.findIndex(obj => obj.id === rows[0].id);
        if(index == -1){
          this.$message.warn('请选择要编辑的入库信息！')
          return;
        }
        let props = {}
        props.index = index
        props.row = rows[0]
        this.$refs.details.open(props,this.bussStorageDetailTable.dataSource)
      },
      onSearchSuper(){
        //上级单据
        if(typeof this.model.storageType === 'undefined'){
          this.$message.error('请选择入库类型！')
        }else if(this.model.storageType == 0){
          this.addMaterial();
        }else if(this.model.storageType == 1){
          this.onSearchNotice();
        }else {
          alert('小组作业报')
        }
      },
      handlerSelect(data){
        this.model.supplierId = data
      },
      dictChanded(){
        this.clearData()
        this.$set(this.model,'materialType',null)
        this.$set(this.model,'packageType',null)
      },
      clearData(){
        this.model.superiorCode = ''
        this.bussStorageDetailTable.dataSource = []
        this.model.supplierId = ''
        this.model.supplierName = ''
      },
      goodOk(rows){
        let _this = this;
        rows.forEach((item,index)=>{
          let obj = {
            materialId: item.id,
            materialName: item.name,
            materialCode: item.code,
            spec: item.noneSpec,
            rowNum: this.getRowNum(),
            storageType: this.model.storageType,
            materialTypeName: item.categoryCodeText.split(" ")[0],
            warehouseDate: moment(new Date()).format('YYYY-MM-DD'),
            qcStatus: this.model.storageType == 1 ? 1 : 0
          }
          this.bussStorageDetailTable.dataSource.push(obj)
        })
        // this.formatterDatas();
      },
      addMaterial(){
        this.$nextTick(() => {
          this.$refs.good.add()
        })
      },
      onSearchNotice(){
        this.$nextTick(() => {
          this.$refs.notice.add()
        })
      },
      noticeOk({rows,callback}){
        const row = rows[0]
        this.bussStorageDetailTable.loading = true
        this.addNoticed(rows)
        this.bussStorageDetailTable.loading = false
        // this.$set(this.model,'superiorCode',row.code)
        // this.$set(this.model,'supplierId',row.supplierId)
        // this.$set(this.model,'supplierName',row.supplierName)
        // getAction('/business/bussStorageNotice/queryBussStorageNoticeMaterialByMainId',{id: row.id}).then(res=>{
        //   this.addBefore()
        //   const { result } = res
        //   result.forEach((item,index)=>{
        //     let obj = {
        //       noticeDetailId: item.id,
        //       num: item.actualNum,
        //       superiorCode: item.code,
        //       storageType: this.model.storageType
        //     }
        //     this.bussStorageDetailTable.dataSource.push(obj)
        //   })
        // }).finally(()=>{
        //   this.bussStorageDetailTable.loading = false
        // })
        callback(true)
        // this.formatterDatas();
      },
      addBefore(){
        this.bussStorageDetailTable.dataSource = []
      },
      addAfter(){

      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        let _this = this
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.bussStorageDetail.list, params, this.bussStorageDetailTable,(res=>{
            // this.formatterDatas()
          }))

        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
          if(allValues.tablesValue[0].tableData.length == 0){
            this.$message.error('请添加收货信息！')
            return false;
          }
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let _this = this;
        let main = Object.assign(this.model, allValues.formValue)

        return {
          ...main, // 展开
          bussStorageDetailList:  _this.processingData(allValues.tablesValue[0].tableData),
          bussStorageCarList: _this.processingData(allValues.tablesValue[1].tableData),
        }
      },
      processingData(data){
        let newJsonArray = data.map(item => {
          return { ...item, id: item.id && item.id.indexOf('row')>=0?'':item.id  };
        });
        return newJsonArray;
      },
      validateError(msg){
        this.$message.error(msg)
      },
      // formatterDatas(){
      //   // 格式化数据
      //   if(this.bussStorageDetailTable.dataSource.length > 0){
      //     this.bussStorageDetailTable.dataSource.forEach(item=>{
      //        if(this.model.storageType == 0){
      //          item.storageType = '手动入库'
      //        }else if(this.model.storageType == 1){
      //          item.storageType = '采购入库'
      //        }else{
      //          item.storageType = '成品入库'
      //        }
      //     })
      //   }
      // },
      handleDetailsConfirm({row,datasource,index, callback}) {
        // 校验当前行 app.$refs['formInline']
        if(datasource === this.bussStorageDetailTable.dataSource){
          this.$refs.mainForm.validate(valid=>{
            this.detailsConfirm(valid,row,datasource,index,callback);
            this.tableRef.resetScrollTop();
          })
        }
      },
      detailsConfirm(valid,row,datasource,index, callback){
        if (valid) {
          callback(true)
          if (typeof index !== 'undefined') {
            Object.assign(datasource[index], row);
          }else{
            datasource.push(row);
          }
        } else {
          callback(false)
          this.$message.warn('校验失败')
        }
      },
      getRowNum(){
        let source = this.bussStorageDetailTable.dataSource
        if(source.length === 0){
          return '0001'
        }
        let { rowNum } = source[source.length-1]
        let nextRowNum = Number(rowNum) + 1;
        if(nextRowNum < 10){
          return '000'+ nextRowNum;
        }else if(nextRowNum < 100){
          return '00'+ nextRowNum;
        }else if(nextRowNum < 1000){
          return '0'+ nextRowNum;
        }else {
          return String(nextRowNum)
        }
      }

    }
  }
</script>

<style scoped>
</style>